import { Feature } from "ol";
import { Polygon } from "ol/geom";
import GeoJSON from "ol/format/GeoJSON";
import { GeoJSONManager } from "./layerDataManager";
// 安全射界
interface Sector {
    radius1: number,
    radius2: number,
    angleStart: number,
    angleEnd: number
}
let features = []
export const SafeShootingRealm = {
    // 初始化射界
    initShootingRealm(data: Array<any>, center: [number, number], sector: Array<Sector> = []) {
        if (data.length == 0) {
            console.log('请提供厂家可匹配的数据!');
            return
        }
        // 获取圆feature
        const circleFeature = this.drawACircle(data, center)
        //  获取线feature
        const lineFeature = this.drawLine(data[0].distance, center)
        // 获取仰角feature
        const elevationFeature = this.generateElevation(data, center)
        // 获取公里标识
        const kilometreFeature = this.generateDistanceIdentification(center)
        // 将数据整合
        features = circleFeature.concat(lineFeature)
        features = features.concat(elevationFeature)
        features = features.concat(kilometreFeature)
        // 获取扇形feature
        if (sector.length > 0) {
            sector.forEach(item => {
                const sectorFeature = this.generateSectorShape(center, item.radius1, item.radius2, item.angleStart, item.angleEnd)
                features.push(sectorFeature)
            })
        }
        // 获取整体layer
        const layer = GeoJSONManager.loadMoreGeoJSON(features)

        return layer
    },
    // 生成仰角文本
    generateElevation(data: Array<any>, center: [number, number]) {
        let elevationFeature: any[] = []
        data.forEach(item => {
            const lonLat = this.metersToCoordinate(center[0], center[1], item.distance, 0)
            elevationFeature.push({ data: lonLat, label: item.angle + "°" })
        })
        const feature = this.drawPoint(elevationFeature)
        return feature
    },
    // 生成扇形 
    generateSectorShape(center: [number, number], radius1: number, radius2: number, angleStart: number, angleEnd: number) {
        // 假设中心点是经纬度 (longitude, latitude)
        const lon = center[0];  // 经度
        const lat = center[1];  // 纬度

        // 计算外圈
        let circleOuter: [number, number][] = [];
        for (let i = angleStart; i < angleEnd; i++) {
            circleOuter.push(this.metersToCoordinate(lon, lat, radius1, i))
        }
        // 计算内圈
        let circleInner: [number, number][] = [];
        for (let i = angleStart; i < angleEnd; i++) {
            circleInner.push(this.metersToCoordinate(lon, lat, radius2, i))
        }
        // 合并路径
        circleInner.unshift(circleOuter[0])
        circleInner.push(circleOuter[circleOuter.length - 1])

        const coordinates = [circleInner.concat(circleOuter.reverse())]

        const sectorGeometry = new Polygon(coordinates);

        // 创建扇形Feature并设置样式
        const sectorFeature = new Feature({
            geometry: sectorGeometry
        });

        const geoJson = new GeoJSON();
        const writeFeature = geoJson.writeFeatureObject(sectorFeature);

        return writeFeature;
    },
    // 绘制圆
    drawACircle(data: Array<any>, center: [number, number], isDashed = true): Array<any> {
        let circleData = []
        for (let j = 0; j < data.length; j++) {
            const element = data[j];
            let circleItem = []
            for (let i = 0; i < 361; i++) {
                circleItem.push(this.metersToCoordinate(center[0], center[1], element.distance, i))
            }
            const geoJson = GeoJSONManager.convertToLine(circleItem)
            // 检查并合并属性
            // 设置样式
            geoJson.properties = {
                ...geoJson.properties, // 保留原有的属性
                style: {
                    isDashed: isDashed,
                    strokeWidth: 1
                }
            };
            circleData.push(geoJson)
        }
        return circleData
    },

    // 绘制线
    drawLine(distance: number, center: [number, number]): Array<any> {
        let lineData = []
        let lineItem = []
        let pointData = []
        for (let i = 0; i < 360; i += 15) {
            lineItem = []
            lineItem.push(center)
            lineItem.push(this.metersToCoordinate(center[0], center[1], distance, i))
            const geoJson = GeoJSONManager.convertToLine(lineItem);
            if (![0, 45, 90, 135, 180, 225, 270, 315].includes(i)) {
                // 设置样式
                geoJson.properties = {
                    ...geoJson.properties, // 保留原有的属性
                    style: {
                        isDashed: true,
                        strokeWidth: 1
                    }
                };
            } else {
                // 在此添加角度显示信息
                pointData.push({ data: this.metersToCoordinate(center[0], center[1], distance, i), label: i + "°" })
            }
            lineData.push(geoJson)
        }
        const pointDatas = this.drawPoint(pointData)
        const lineDatas = lineData.concat(pointDatas)
        return lineDatas
    },

    // 创建标签 原理加载点，其实只显示text
    drawPoint(coord: Array<any>, radius = 5) {
        let pointFeature: any[] = []
        coord.forEach(item => {
            let geoJson = GeoJSONManager.convertToPoint(item.data)
            // 设置样式
            geoJson.properties = {
                ...geoJson.properties, // 保留原有的属性
                style: {
                    color: 'blue',
                    text: item.label,
                    radius
                }
            };
            pointFeature.push(geoJson)
        })
        return pointFeature
    },
    // 生成距离标识   ,,, 默认向东 90度计算
    generateDistanceIdentification(center: [number, number]) {
        let kilometreFeature = []
        let kilometreCircleFeature = []
        for (let i = 1; i <= 10; i++) {
            // 获取相应角度的 坐标
            const coordinate = this.metersToCoordinate(center[0], center[1], i * 1000, 90)
            if(i == 1 || i == 10){
                kilometreFeature.push({ data: coordinate, label: i + "km" })
            }else{
                kilometreFeature.push({ data: coordinate, label: "" })
            }
           
        }

        const feature = this.drawPoint(kilometreFeature, 4)
        kilometreCircleFeature.push({ distance: 1000 }, { distance: 10000 })
        const circleFeature = this.drawACircle(kilometreCircleFeature, center, false)
        feature.push(...circleFeature)
        return feature
    },
    // 辅助工具
    // 根据方向和距离偏移坐标   距离以米为单位
    metersToCoordinate(lon: number, lat: number, distanceInMeters: number, angle: number): [number, number] {
        // 角度调整：根据新的系统将角度转换为标准方向
        // 如果是0度为西，90度为南，180度为东，270度为北
        const adjustedAngle = (450 - angle) % 360;  // 调整角度使其符合标准方向，逆时针旋转

        // 计算经度和纬度的偏移量（在 Web Mercator 坐标系下）
        const earthRadius = 6371000; // 地球半径，单位为米
        const deltaLat = distanceInMeters * Math.sin((adjustedAngle * Math.PI) / 180) / earthRadius;
        const deltaLon = distanceInMeters * Math.cos((adjustedAngle * Math.PI) / 180) / (earthRadius * Math.cos((lat * Math.PI) / 180));

        // 计算新的经纬度
        const newLat = lat + deltaLat * 180 / Math.PI;  // 转换为度
        const newLon = lon + deltaLon * 180 / Math.PI;  // 转换为度

        return [newLon, newLat];
    }
}


